package com.example.demo.Controller;

import com.example.demo.Entity.Book;
import com.example.demo.Entity.AdminApplication;
import com.example.demo.Entity.IllegalAction;
import com.example.demo.Entity.ShopUser;
import com.example.demo.Entity.UnlockApplication;
import com.example.demo.Service.*;
import com.example.demo.Util.UserApplicationAndActionUtil;
import com.example.demo.Util.UserUtil;
import com.example.demo.Vo.Response;
import com.example.demo.Vo.UserVo;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private UserApplicationService userApplicationService;
    @Autowired
    private UserActionService userActionService;
    @Autowired
    private BookService bookService;

    @PostMapping("/api/send_email")
    public Response sendEmail(@RequestBody Map<String, String> reMap, HttpServletRequest request) {
        Response response;
        String email = reMap.get("email");
        try {
            emailService.sendMimeMail(email, request.getSession());
            response = Response.createBySuccessMessage("验证码发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/register")
    public Response newUserRegister(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String uid = reMap.get("uid");
        String password = reMap.get("password");
        String rePassword = reMap.get("re_password");
        String email = reMap.get("email");
        String verificationCode = reMap.get("verificationCode");
        try {
            ShopUser repeatNameUser = userService.selectUserByUserID(uid);
            ShopUser repeatEmailUser = userService.selectUserByUserEmail(email);
            UserVo userVo = new UserVo(uid, password, email, verificationCode);
            System.out.println(userVo.getEmail());
            response = userService.checkUserVar(userVo);
            if (response == null) {
                if (repeatNameUser != null) {
                    response = Response.createByErrorMessage("用户名已存在");
                } else if (repeatEmailUser != null) {
                    response = Response.createByErrorMessage("用户邮箱已存在");
                } else if (!password.equals(rePassword)) {
                    response = Response.createByErrorMessage("两次密码输入不一致，请重新输入");
                } else {
                    if (userService.registerNewUser(userVo, request.getSession())) {
                        response = Response.createBySuccessMessage("用户注册成功！");
                    } else {
                        response = Response.createByErrorMessage("验证码错误");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/login")
    public Response userLogin(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String key = reMap.get("key");
        String password = reMap.get("password");
        try {
            ShopUser user;
            if (UserUtil.checkUserID(key)) {
                user = userService.selectUserByUserID(key);
            } else if (UserUtil.checkUserEmail(key)) {
                user = userService.selectUserByUserEmail(key);
            } else {
                return Response.createByErrorMessage("请输入正确格式的邮箱或用户名");
            }
            if (user != null) {
                if (user.getUserPassword().equals(password)) {
                    HttpSession session = request.getSession();
                    if (session.getAttribute("uid") != null && session.getAttribute("uid").toString().equals(user.getUserID())) {
                        response = Response.createBySuccessMessage("用户已登录！");
                    } else {
                        if (userService.checkUseAvailable(user.getUserID())) {
                            session.setAttribute("uid", user.getUserID());
                            response = Response.createBySuccessMessage("用户登录成功！");
                        } else {
                            response = Response.createByErrorMessage("您正被封禁！解封时间为：" + UserUtil.getSimpleDateFormat().format(user.getUnlockDate()));
                        }
                    }
                } else {
                    response = Response.createByErrorMessage("密码错误");
                }
            } else {
                response = Response.createByErrorMessage("用户不存在，请先注册");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @GetMapping("/api/my_info")
    public Response userInfo(HttpServletRequest request) {
        Response response = null;
        Map<String, ShopUser> map = new HashMap<String, ShopUser>();
        try {
            String uid = (String) request.getSession().getAttribute("uid");
            ShopUser user = userService.selectUserByUserID(uid);
            map.put("user", user);
            response = Response.createBySuccess("成功获取用户信息", map);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/change_password")
    public Response changeUserPassword(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String oldPassword = reMap.get("old_password");
        String newPassword = reMap.get("new_password");
        String reNewPassword = reMap.get("re_new_password");
        Date date = new Date();
        Map<String, Date> map = new HashMap<>();
        map.put("changePasswordDate", date);
        try {
            String uid = (String) request.getSession().getAttribute("uid");
            ShopUser user = userService.selectUserByUserID(uid);
            String trueOldPassword = user.getUserPassword();
            if (oldPassword.equals("") || newPassword.equals("") || reNewPassword.equals("")) {
                response = Response.createByErrorMessage("以上信息均不能为空");
            } else {
                if (!oldPassword.equals(trueOldPassword)) {
                    response = Response.createByErrorMessage("旧密码输入错误，请重新输入");
                } else if (!reNewPassword.equals(newPassword)) {
                    response = Response.createByErrorMessage("新密码两次输入不一致，请重新输入");
                } else if (!UserUtil.checkUserPassword(newPassword)) {
                    response = Response.createByErrorMessage("新密码格式错误，密码必须包含大小写字母和数字的组合，可以使用特殊字符，长度在8-20之间");
                } else {
                    userService.changePasswordByUserID(user.getUserID(), newPassword);
                    response = Response.createBySuccess("修改密码成功", map);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @GetMapping("/api/logout")
    public Response userLogout(HttpServletRequest request) {
        Response response = null;
        try {
            HttpSession session = request.getSession();
            session.removeAttribute("uid");
            response = Response.createBySuccessMessage("注销登录成功");
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/find_change_password")
    public Response findChangeUserPassword(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String password = reMap.get("password");
        String rePassword = reMap.get("re_password");
        String email = reMap.get("email");
        String verificationCode = reMap.get("verificationCode");
        Date date = new Date();
        Map<String, Date> map = new HashMap<>();
        map.put("changePasswordDate", date);
        try {
            ShopUser user;
            if (UserUtil.checkUserEmail(email)) {
                user = userService.selectUserByUserEmail(email);
                if (user == null) {
                    response = Response.createByErrorMessage("该邮箱未被注册");
                } else if (!UserUtil.checkUserPassword(password)) {
                    response = Response.createByErrorMessage("新密码格式错误，密码必须包含大小写字母和数字的组合，可以使用特殊字符，长度在8-20之间");
                } else if (!password.equals(rePassword)) {
                    response = Response.createByErrorMessage("两次输入不一致，请重新输入");
                } else {
                    if (userService.findPasswordByUserEmail(email, verificationCode, password, request.getSession())) {
                        response = Response.createBySuccess("重置密码成功", map);
                    } else {
                        response = Response.createByErrorMessage("验证码错误");
                    }
                }
            } else {
                return Response.createByErrorMessage("请输入正确格式的邮箱或用户名");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/change_info")
    public Response changeUserInfo(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String name = reMap.get("name");
        String signature = reMap.get("signature");
        String address = reMap.get("address");
        String pictureBase = reMap.get("pictureBase");
        Map<String, Date> map = new HashMap<>();
        Date date = new Date();
        map.put("changeInfoDate",date);
        try {
            String uid = (String) request.getSession().getAttribute("uid");
            System.out.println(uid);
            userService.changeInfoByUserID(uid, name, signature, address, pictureBase);
            response = Response.createBySuccess("修改成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/apply_admin")
    public Response applyToAdmin(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        try {
            String uid = (String) request.getSession().getAttribute("uid");
            ShopUser user = userService.selectUserByUserID(uid);
            AdminApplication adminApplication = userApplicationService.selectAdminApplicationByUserID(uid);
            if (user.isAdmin()) {
                response = Response.createByErrorMessage("您已是管理员");
            } else if (adminApplication != null) {
                response = Response.createByErrorMessage("您的上一次申请未被处理");
            } else {

                adminApplication = UserApplicationAndActionUtil.createAdminApplication(uid);
                userApplicationService.addNewAdminApplication(adminApplication);
                response = Response.createBySuccessMessage("申请已发送");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/apply_unlock")
    public Response applyUnlockUser(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String key = reMap.get("key");
        String reason = reMap.get("reason");
        try {
            ShopUser user;
            if (UserUtil.checkUserID(key)) {
                user = userService.selectUserByUserID(key);
            } else if (UserUtil.checkUserEmail(key)) {
                user = userService.selectUserByUserEmail(key);
            } else {
                return Response.createByErrorMessage("请输入正确格式的邮箱或用户名");
            }
            if (user == null) {
                response = Response.createByErrorMessage("不存在该用户");
            } else if (userService.checkUseAvailable(user.getUserID())) {
                response = Response.createByErrorMessage("您未被封禁");
            } else {
                UnlockApplication unlockApplication = userApplicationService.selectUnlockApplicationByUserID(user.getUserID());
                if (unlockApplication != null) {
                    response = Response.createByErrorMessage("您的上次申请未被处理");
                } else {
                    unlockApplication = UserApplicationAndActionUtil.createUnlockApplication(user.getUserID(), reason);
                    userApplicationService.addNewUnlockApplication(unlockApplication);
                    response = Response.createBySuccessMessage("申请已发送");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/admin/lock")             //封禁用户
    public Response lockUser(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String uid = reMap.get("uid");

        try {
            if (!userService.checkUseAvailable(uid)) {
                response = Response.createByErrorMessage("该用户已被封禁");
            } else {
                userService.lockUserByUserID(uid);
                IllegalAction illegalAction = UserApplicationAndActionUtil.createLockAction(uid);
                userActionService.addNewAction(illegalAction);
                response = Response.createBySuccessMessage("封禁成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/admin/unlock")               //解封用户
    public Response unlockUser(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String uid = reMap.get("uid");

        try {
            if (userService.checkUseAvailable(uid)) {
                response = Response.createByErrorMessage("该用户未被封禁");
            } else {
                userService.unlockUserByUserID(uid);
                response = Response.createBySuccessMessage("解封成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }


    @GetMapping("/api/admin/apply_admin_list")              //查看申请管理员列表
    public Response getAdminApplication(HttpServletRequest request) {
        Response response = null;
        Map<String, List<AdminApplication>> map = new HashMap<String, List<AdminApplication>>();
        try {
            List<AdminApplication> adminApplicationList = userApplicationService.selectAllAdminApplication();
            if (adminApplicationList.isEmpty()) {
                response = Response.createBySuccessMessage("没有申请成为管理员用户");
            } else {
                map.put("adminApplication", adminApplicationList);
                response = Response.createBySuccess("以下为申请成为管理员用户", map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/admin/user_illegal_action")              //查看单个用户的非法记录
    public Response getUserIllegalInfo(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String uid = reMap.get("uid");
        Map<String, List<IllegalAction>> map = new HashMap<String, List<IllegalAction>>();
        try {
            List<IllegalAction> illegalActionList = userActionService.selectIllegalByUserID(uid);
            if (illegalActionList.isEmpty()) {
                response = Response.createBySuccessMessage("该用户没有非法记录");
            } else {
                map.put("illegalAction", illegalActionList);
                response = Response.createBySuccess("以下为该用户非法记录", map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @GetMapping("/api/admin/all_illegal_action_list")               //查看所有用户非法记录
    public Response getAllIllegalInfo(HttpServletRequest request) {
        Response response = null;
        Map<String, List<IllegalAction>> map = new HashMap<String, List<IllegalAction>>();
        try {
            List<IllegalAction> illegalActionList = userActionService.selectAllIllegalAction();
            if (illegalActionList.isEmpty()) {
                response = Response.createBySuccessMessage("没有任何非法记录");
            } else {
                map.put("illegalAction", illegalActionList);
                response = Response.createBySuccess("以下为所有用户非法记录", map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @GetMapping("/api/admin/apply_unlock_list")             //查看申请解封用户列表
    public Response getUnlockApplication(HttpServletRequest request) {
        Response response = null;
        Map<String, List<UnlockApplication>> map = new HashMap<String, List<UnlockApplication>>();
        try {
            List<UnlockApplication> unlockApplicationList = userApplicationService.selectAllUnlockApplication();
            if (unlockApplicationList.isEmpty()) {
                response = Response.createBySuccessMessage("没有申请解封用户");
            } else {
                map.put("unlockApplication", unlockApplicationList);
                response = Response.createBySuccess("以下为申请解封用户", map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/admin/deal_admin_application")       //处理管理员申请
    public Response dealUserAdminApplication(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String uid = reMap.get("uid");
        boolean ok = reMap.get("ok").equals("true") ? true : false;
        try {
            AdminApplication adminApplication = userApplicationService.selectAdminApplicationByUserID(uid);

            if (adminApplication == null) {
                response = Response.createByErrorMessage("该用户请求已被其他管理员处理");
            } else {
                userService.changeAdminByUserID(uid, ok);
                userApplicationService.deleteByUserID(uid);
                if (ok) {
                    response = Response.createBySuccessMessage("已同意该用户管理员申请");
                } else {
                    response = Response.createBySuccessMessage("已拒绝该用户管理员申请");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/admin/deal_unlock_application")  //处理用户解封申请
    public Response dealUserUnlockApplication(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String uid = reMap.get("uid");
        boolean ok = reMap.get("ok").equals("true") ? true : false;
        try {
            UnlockApplication unlockApplication = userApplicationService.selectUnlockApplicationByUserID(uid);

            if (unlockApplication == null) {
                response = Response.createByErrorMessage("该用户请求已被其他管理员处理");
            } else {
                userApplicationService.changeUnlockUsedByUserID(uid, true);
                if (ok) {
                    userService.unlockUserByUserID(uid);
                    response = Response.createBySuccessMessage("已同意该用户解封申请");
                } else {
                    response = Response.createBySuccessMessage("已拒绝该用户解封申请");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

}
